package com.utc.fjc.command.newpart;

import com.teamcenter.rac.aif.ICommandListener;
import com.teamcenter.rac.aif.IPerspectiveDef;
import com.teamcenter.rac.aif.IPerspectiveDefService;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.aifrcp.AifrcpPlugin;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.services.IOpenService;
import com.teamcenter.rac.ui.commands.create.bo.NewBOOperation;
import com.teamcenter.rac.ui.commands.create.bo.NewBOWizard;
import com.teamcenter.rac.ui.common.RACUIUtil;
import com.teamcenter.rac.util.OSGIUtil;
import com.utc.teamcenter.common.util.TCUtil;

public class NewPartOperation extends NewBOOperation {

	public static String PSEPerspective = "com.teamcenter.rac.pse.PSEPerspective";

	protected void pasteNewComponent(ICommandListener arg0) throws Exception {
		InterfaceAIFComponent[] targets = AIFUtility.getCurrentApplication()
				.getTargetComponents();

		if ((targets != null) && (targets.length > 0)) {
			TCComponent tcComp = (TCComponent) targets[0];

			if ((tcComp != null)
					&& ((tcComp instanceof TCComponentItemRevision))) {
				// if (tcComp.getType().equalsIgnoreCase(PartRev)) {
				if ((this.wizard instanceof NewBOWizard)) {
					this.wizard.setRevisionFlag(true);
				}
				// }
			}

			if ((tcComp != null) && (tcComp instanceof TCComponentFolder)) {
				super.pasteNewComponent(arg0);
			} else {
				TCComponentFolder newstuff = TCUtil.getTCSession().getUser()
						.getNewStuffFolder();
				newstuff.add("contents", this.newComponent);
			}

		}
		// super.pasteNewComponent(arg0);

		if (((targets != null) && (targets.length == 0)) || (targets == null)) {
			String curActivePers = AIFUtility.getCurrentPerspectiveDef()
					.getId();

			if ((curActivePers != null)
					&& (curActivePers.equals(PSEPerspective))) {
				IPerspectiveDefService pdSvc = (IPerspectiveDefService) OSGIUtil
						.getService(AifrcpPlugin.getDefault(),
								IPerspectiveDefService.class);

				IPerspectiveDef perspDef = pdSvc
						.findByPerspectiveId(PSEPerspective);

				String filter = RACUIUtil.getApplicationServiceFilter(perspDef);
				IOpenService openService = RACUIUtil.getOpenService(filter);

				if ((openService != null) && (this.newComponent != null)) {
					openService.open(this.newComponent);
				}

				perspDef.openPerspective();
			}
		}
	}
}
